define(function(require, exports, module) {
    'use strict';

    var rk = require('rk');
    //




    $.widget('rk.createTaskDialogCtrl', $.rk.oaDialogCtrl, {
        options: {
            owner: null // 为他人创建时的默认负责人
        },
        _create: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            var url = '/json/crm_func/get-crm-func.action';
            rk.post(url, {}).done(function(json) {
                if (json.status == 0) {
                    SESSION.func = json.data.permission.func;

                    require.async('oa/tmpl/task/tpl_task_dialog_create.tpl', function(tmpl) {
                        SESSION.wanxue = WANXUE;
                        var html = rk.templateText(tmpl, SESSION);
                        elem.html(html);
                        me._initTaskCreate();
                    });
                } else {
                    $.msg(rk.i18n('LOAD_ERROR'));
                }
            });

            /*require.async('oa/tmpl/task/tpl_task_dialog_create.tpl', function(tmpl) {
                SESSION.wanxue = WANXUE;
                var html = rk.templateText(tmpl, SESSION);
                elem.html(html);
                me._initTaskCreate();
            });*/
        },
        _init: function() {
            var me = this;
            var elem = me.element;
            me.getBtn('save').on('click', $.proxy(me.okClicked, me));
        },
        _initTaskCreate: function() {
            var me = this;
            var $dialog = me.element;
            var opt = me.options;
            if (opt.forSelf) {
                $dialog.find('div.js-first-step').hide();
                me.getBtn('prevstep').hide();
                me.getBtn('nextstep').hide();
                var $reminder = $dialog.find('#dlt_reminder');
                $reminder.selectmenu({
                    appendTo: 'body'
                });
            } else {
                $dialog.find('div.js-joiner').hide();
                $dialog.find('div.js-second-step').hide();
                me.getBtn('prevstep').hide();
                me.getBtn('save').hide();
                me.getBtn('prevstep').on('click', function(evt) {
                    evt.preventDefault();
                    $dialog.find('div.js-first-step').show();
                    $dialog.find('div.js-second-step').hide();
                    $dialog.find('a[act="prevstep"],a[act="save"]').hide();
                    me.getBtn('prevstep').hide();
                    me.getBtn('save').hide();
                    me.getBtn('nextstep').show();
                    rk.repositionDialog();
                });
                me.getBtn('nextstep').on('click', function(evt) {
                    evt.preventDefault();
                    var $el = $dialog.find(':input.js-owner'),
                        ownerId = $el.attr('userid');
                    if ($.trim(ownerId) == '' || $.trim($el.val()) == '') {
                        $.msg(rk.i18n('TASK_TEXT_8'));
                        return;
                    }
                    $dialog.find('div.js-first-step').hide();
                    $dialog.find('div.js-second-step').show();
                    me.getBtn('prevstep').show();
                    me.getBtn('save').show();
                    me.getBtn('nextstep').hide();
                    var $reminder = $dialog.find('#dlt_reminder');
                    $reminder.selectmenu({
                        appendTo: 'body'
                    });
                });

                var $owner = $dialog.find(':input.js-owner').rkUser({
                    onSelect: function(userId, userName) {

                    }
                });
                if (this.options.owner) {
                    $owner.rkUser('setUser', this.options.owner.value, this.options.owner.label);
                }

                if (opt.otherUser) {
                    $dialog.find(':input.js-owner').rkUser('setUser', opt.otherUser.id, opt.otherUser.name);
                }
                $dialog.find(':input.js-joiner').snsmultipeopleselector({
                    position: {
                        my: 'left top+2'
                    },
                    onUpdate: function() {
                        rk.repositionDialog();
                    }
                });
            }

            $dialog.on('focus', 'input.js-taskname', function() {
                var $ipt = $(this),
                    $drop = $ipt.next();
                $drop.slideDown(50);
                $drop.position({
                    my: 'left top',
                    at: 'left bottom',
                    of: $ipt,
                    collision: 'fit'
                });
                $('body').on('click', function(evt) {
                    if (evt.target != $ipt.get(0)) {
                        $drop.slideUp(50);
                    }
                });
            });

            $dialog.on('click', 'div.js-drop li', function() {
                var $li = $(this),
                    $drop = $li.parents('.js-drop'),
                    $ipt = $drop.prev();
                $ipt.val($li.text());
                $drop.slideUp(50);
            });
            var now = new Date();
            now.setHours(now.getHours() + 1);
            now.setMinutes(0);
            now.setSeconds(0);
            var defDate = moment(now).format('YYYY-MM-DD'),
                defTime = moment(now).format('HH:mm');
            var $dateIpt = $dialog.find('input.date').val(defDate),
                $timeIpt = $dialog.find('input.time').val(defTime);
            $dateIpt.datepicker({
                changeYear: true,
                changeMonth: true
            });
            $timeIpt.timepicker({});

            $dialog.on('click', 'a.task_add_people', function(evt) {
                evt.preventDefault();
                var $li = $(this).parent().empty(),
                    $ul = $li.parent(),
                    $div = $ul.parent();
                $div.empty().append('<div class="name_select"><input name="joiner" type="text" class="joiner"/></div>');
                $div.find(':input').snsmultipeopleselector({
                    position: {
                        my: 'left top+2'
                    },
                    onUpdate: function() {
                        rk.repositionDialog();
                    }
                });
            });

            $dialog.on('click', 'a.js-relate', function(evt) {
                evt.preventDefault();
                var $lnk = $(this),
                    $div = $lnk.next(),
                    $business = $div.find('#dlt_relate_business'),
                    $entry = $div.find('span.js-task-relate');
                $lnk.hide();
                $div.show();
                $business.selectmenu({
                    appendTo: 'body'
                });
                $business.on('selectmenuchange', function(evt) {
                    var value = $(this).val();
                    var belongName = {
                        1: SESSION.keywords.account,
                        3: SESSION.keywords.opportunity,
                        2: SESSION.keywords.contact,
                        11: SESSION.keywords.lead,
                        6: SESSION.keywords.campaign,
                        66: SESSION.keywords.agent,
                        67: SESSION.keywords.terminal
                    }[value];
                    $entry.find('input.js-autocomplete').trigger('destroy');
                    var $relBusiness = $('<input type="text" class="js-autocomplete"/>');
                    $relBusiness.appendTo($entry.empty()).autocomplete({
                        source: function(request, response) {
                            var key = request.term;
                            $.ajax({
                                url: {
                                    1: '/json/oa_search/search-account.action?pageNo=1&accountTypes=1',
                                    3: '/json/oa_search/search-opp.action?pageNo=1',
                                    2: '/json/oa_search/search-contact.action?pageNo=1',
                                    11: '/json/oa_search/search-lead.action?pageNo=1',
                                    6: '/json/oa_search/search-campaign.action?pageNo=1',
                                    66: '/json/crm_search/all-accounts.action?accountType=4&pageNo=1',
                                    67: '/json/crm_search/all-accounts.action?accountType=5&pageNo=1'
                                }[value] + '&key=' + request.term,
                                type: 'GET',
                                dataType: "json",
                                success: function(resultData, status) {
                                    var id;
                                    if (resultData.length > 0) {
                                        for (var i = 0; i < resultData.length; i++) {
                                            if (resultData[i].label == key) {
                                                id = resultData[i].value;
                                            }
                                        }
                                    } else {
                                        $("#search_msg").html(belongName + rk.i18n('TASK_TEXT_9')).show();
                                        $("#taskRelObject").val("");
                                    }
                                    if (id != undefined) {
                                        $("#search_msg").html(rk.i18n('TASK_TEXT_10') + belongName).show();
                                        $("#taskRelObject").val(id);
                                    } else {
                                        $("#search_msg").html(belongName + rk.i18n('TASK_TEXT_9')).show();
                                        $("#taskRelObject").val("");
                                    }
                                    response(resultData);
                                },
                                error: function() {
                                    response([]);
                                }
                            });
                        },
                        select: function(event, ui) {
                            var id = ui.item.value;
                            $("#taskRelObject").val(id);
                            $relBusiness.val(ui.item.label);
                            $("#search_msg").html(rk.i18n('TASK_TEXT_10') + belongName);
                            return false;
                        }
                    });
                    $entry.append('<span id="search_msg" class="tip_bottom hidden"></span>');
                });
                $business.trigger('selectmenuchange');
            });

            $dialog.on('click', 'a.more_link', function(evt) {
                evt.preventDefault();
                var $lnk = $(this),
                    $divs = $lnk.nextAll();
                $lnk.hide();
                $divs.show().find('textarea').focus();
                rk.repositionDialog();
            });
            var $upload = $dialog.find('input[name="upd_task_addon"]');
            $dialog.find('.fileinput-box').multifileuploader({
                url: '/json/global_uploadify/upload.action'
            });
            /*$upload.upload({
                uploadify_setting: {
                    uploader: '/json/global_uploadify/upload.action', //String
                    multi: false,
                    onSelect: function(file) {
                        if (me.file) {
                            $upload.uploadify("cancel", me.file.id);
                        }
                    },
                    onUploadStart: function(file) {
                        $upload.uploadify('settings', 'formData', {
                            'pageTenantId': SESSION.tenantId,
                            'uploadFileName': file.name,
                            'uploadContentType': file.type.slice(1)
                        });
                    },
                    onUploadSuccess: function(file, data, response) {
                        data = $.parseJSON(data);
                        if (data.status == 0) {
                            data = $.parseJSON(data.data);
                            me.file = file;
                            me.fileData = JSON.stringify({
                                fileUrl: data.fileUrl,
                                fileName: file.name,
                                fileLength: data.fileLength
                            });
                        } else {
                            $.msg(rk.i18n('TASK_TEXT_11') + data.statusText);
                        }
                        rk.repositionDialog();
                    },
                    onCancel: function(file) {
                        $dialog.find('input[name="fileUrl"]').val('');
                        me.fileData = '';
                    }
                }
            });*/
        },
        okClicked: function() {
            var me = this;
            var $dialog = me.element;
            var opt = me.options;
            var $el = $dialog.find('input.js-taskname'),
                taskName = $.trim($el.val());
            if (!taskName) {
                $.msg(rk.i18n('TASK_NAME_NOT_BLANK'));
                return $el.focus();
            }
            if (taskName.length > 30) {
                $.msg(rk.i18n('TASK_TEXT_12'));
                return $el.focus();
            }

            var $el = $dialog.find('input.date'),
                date = $.trim($el.val());
            if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) {
                $.msg(date ? rk.i18n('TASK_INPUT_END_DATE') : rk.i18n('TASK_SELECT_END_DATE'));
                return $el.focus();
            }

            var $el = $dialog.find('input.time'),
                time = $.trim($el.val());
            if (!/^\d{2}:\d{2}$/.test(time)) {
                $.msg(time ? rk.i18n('TASK_INPUT_END_TIME') : rk.i18n('TASK_SELECT_END_TIME'));
                return $el.focus();
            }

            var $el = $dialog.find('#dlt_reminder'),
                reminder = $el.val();

            if (!opt.forSelf) {
                var $el = $dialog.find(':input.js-owner'),
                    ownerId = $el.attr('userid');
                var $el = $dialog.find(':input.js-joiner'),
                    joiner = (($el.data('wtype') == 'snsmultipeopleselector' ? $el.snsmultipeopleselector('val') : '') || []).join(',');
            } else {
                var $el = $dialog.find(':input.joiner'),
                    joiner = (($el.data('wtype') == 'snsmultipeopleselector' ? $el.snsmultipeopleselector('val') : '') || []).join(',');
            }

            var $el = $dialog.find('div.bussiness_select'),
                business, businessIds;
            if ($el.is(':visible')) {
                business = $('#dlt_relate_business').val();
                businessIds = $('#taskRelObject').val();
                //$el = $dialog.find('input.js-autocomplete');
                //if ($el.attr('type').toLowerCase() == 'hidden') {
                //    businessIds = $el.val();
                //} else {
                //    businessIds = $el.find('option').map(function (_, option) {
                //        return $(option).attr('value');
                //    }).get().join(',');
                //}
            }

            var $upload = $dialog.find('.fileinput-box');
            if ($upload.multifileuploader('status').uploading) {
                return $.msg(rk.i18n('文件上传中...'));
            }
            var files = $upload.multifileuploader('val');

            // if (!files.length) {
            //     return $.msg(rk.i18n('APPS_FILE_CHOOSE_FILE_UPLOAD'));
            // }

            me.fileData = JSON.stringify(files);

            var $el = $dialog.find('textarea'),
                desc = $.trim($el.val());
            if (desc && desc.length > 500) {
                $.msg(rk.i18n('TASK_DESCRIPTION_NOT_MORE_THAN'));
                return $el.focus();
            }
            me.getBtn('save').beLoading();

            //if(window._hmt){_hmt.push(['_trackEvent', 'operate', 'task_add', window.SESSION.tenantName]);}

            $.post('/json/crm_task/save.action', {
                memberIds: joiner,
                attachments: me.fileData,
                reminder: reminder,
                'paramMap.taskName': taskName,
                'paramMap.planFinishDate': date,
                'paramMap.planFinishTime': time,
                'paramMap.belongId': business,
                'paramMap.objectId': businessIds,
                'paramMap.ownerId': opt.forSelf ? SESSION.user.id : ownerId,
                'paramMap.description': desc
            }, null, 'json').done(function(json) {
                if (json.status == 0) {
                    $.msg(rk.i18n('TASK_CREATE_SUCCESS'), 1);
                    me._delay(function() {
                        me.closeMe();
                    });
                    if ($.isFunction(opt.onSuccess)) {
                        opt.onSuccess();
                    }
                } else {
                    me.getBtn('save').unLoading();
                    $.msg(rk.i18n('TASK_CREATE_ERROR'));
                }
            }).fail(function(def, code, message) {
                me.getBtn('save').unLoading();
                def.status != 0 && $.msg(rk.i18n('LOAD_ERROR'));
            });
        }
    });

    return $;
});
